﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;

namespace HttpGet
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine(
                    "Get address not set. pls call like HttpGet http://www.baidu.com [-header=xx:bb;aa:cc] [-save=xxx.xx]");
                return;
            }

            var header = new Dictionary<string, string>();
            string saveTo = null;
            foreach (var s in args)
            {
                if (s.StartsWith("-header"))
                {
                    var kv = s.Split('=', StringSplitOptions.RemoveEmptyEntries);
                    if (kv.Length != 2)
                    {
                        Console.WriteLine("Invalid header");
                        return;
                    }

                    var headerItems = kv[1].Split(';', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var item in headerItems)
                    {
                        var items = item.Split(':', StringSplitOptions.RemoveEmptyEntries);
                        if (items.Length != 2)
                        {
                            Console.WriteLine($"Invalid header: {item}");
                            return;
                        }

                        header[items[0]] = items[1];
                    }
                }
                else if (s.StartsWith("-save"))
                {
                    var kv = s.Split('=', StringSplitOptions.RemoveEmptyEntries);
                    if (kv.Length != 2)
                    {
                        Console.WriteLine("Invalid save to file");
                        return;
                    }

                    saveTo = kv[1];
                }
            }

            try
            {
                Get(args[0], header, saveTo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static void Get(string url, Dictionary<string, string> header, string saveTo)
        {
            var client = new HttpClient();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation(item.Key, item.Value);
            }

            var task = client.GetByteArrayAsync(url);
            task.Wait();
            if (string.IsNullOrWhiteSpace(saveTo))
            {
                Console.WriteLine(Encoding.UTF8.GetString(task.Result));
            }
            else
            {
                var dir = Path.GetDirectoryName(Path.GetFullPath(saveTo, AppDomain.CurrentDomain.BaseDirectory));
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                if (File.Exists(saveTo))
                {
                    saveTo = Path.Combine(dir,
                        $"{Path.GetFileNameWithoutExtension(saveTo)}({DateTime.Now.Ticks}){Path.GetExtension(saveTo)}");
                }

                File.WriteAllBytes(saveTo, task.Result);
                Console.WriteLine($"Save content to {saveTo} succeed.");
            }
        }
    }
}
